<?php

namespace App\Http\Controllers\Admin;

use App\Models\Admin\Goods;
use App\Models\Admin\GoodsCategory;
use App\Models\Admin\StoreGoodsViewPermissions;

class GoodsController extends BaseController
{

    /**
     * 商品分类列表
     */
    public function goodsCategoryList()
    {
        $where['pid'] = $this->requestArr['pid'] ?? null;
        $where['cate_name'] = $this->requestArr['cate_name'];

        $list = GoodsCategory::getList($where);
        $tree = getTree($list);

        return view('admin/goods/categoryList', ['tree' => $tree]);
    }

    /**
     * 添加商品分类
     */
    public function goodsCategoryAdd()
    {
        if ($this->requestMethod == 'POST') {
            $post = $this->requestArr;
            $post['update_user'] = $this->userArr['user_name'];
            $post['create_user'] = $this->userArr['user_name'];
            $result = GoodsCategory::add($post);
            if ($result) {
                successMsg();
            }
            errorMsg('添加失败，请稍后重试');
        }
        $list = GoodsCategory::getList(['pid' => 0]);

        return view('admin/goods/categoryAdd', ['list' => $list]);
    }

    /**
     * 编辑商品分类
     */
    public function goodsCategoryEdit()
    {
        $post = $this->requestArr;
        $id = $post['id'];
        if ($this->requestMethod == 'POST') {
            unset($post['id']);
            $post['update_user'] = $this->userArr['user_name'];
            $result = GoodsCategory::edit($id, $post);
            if ($result) {
                successMsg();
            }
            errorMsg('编辑失败，请稍后重试');
        }
        $info = GoodsCategory::getInfo(['id' => $id]);
        $list = GoodsCategory::getList(['pid' => 0]);

        return view('admin/goods/categoryEdit', ['info' => $info, 'list' => $list]);
    }

    /**
     * 删除商品分类
     */
    public function goodsCategoryDel()
    {
        $id = $this->requestArr['id'];

        # 获取子分类
        $child = GoodsCategory::getList(['pid' => $id]);
        if (count($child)) {
            errorMsg('请先删除子分类，请稍后重试');
        }

        $result = GoodsCategory::del($id);
        if ($result) {
            successMsg();
        }
        errorMsg('删除失败，请稍后重试');
    }



    /********************************************************************
     ******************************商品列表********************************
     ********************************************************************/


    /**
     * 商品列表
     */
    public function goodsList()
    {
        $where['goods_name'] = $this->requestArr['goods_name'];
        $where['is_group'] = "0";
        $where['promotion'] = "0";  // 添加促销商品过滤
        $list = Goods::getList($where);
        if (!empty($where['goods_name'])) {
            $list->appends(['goods_name' => $where['goods_name']])->render();
        }

        return view('admin/goods/goodsList', ['data' => $list]);
    }

    /**
     * ajax 获取商品列表
     */
    public function ajaxGetGoodsList()
    {
        $id = $this->requestArr['id'];
        if ($id) {
            $info = Goods::getInfo(['id' => $id]);
            $info['goods_group'] = json_decode($info['goods_group'], true);
            $goodsGroup = [];
            $goods = Goods::getAll();
            foreach ($goods as $kk => $vv) {
                if ($vv['goods_sale_num'] == null) {
                    $goods[$kk]['goods_sale_num'] = 0;
                }
                if ($vv['is_group'] == 1 || $vv['promotion'] == 1) {
                    unset($goods[$kk]);
                }
            }
            $goods = array_values($goods);
            $list = $goods;
            foreach ($goods as $key => &$val) {
                foreach ($info['goods_group'] as $v) {
                    if ($v['id'] == $val['id']) {
                        unset($goods[$key]);
                        $tmp = $val;
                        $tmp['number'] = $v['number'];
                        $goodsGroup[] = $tmp;
                    }
                }
            }

            $data = ['list' => $list, 'left' => array_values($goods), 'right' => $goodsGroup];
        } else {
            $goods = Goods::getAll();
            foreach ($goods as $key => &$val) {
                if ($val['goods_sale_num'] == null) {
                    $val['goods_sale_num'] = 0;
                }
                if ($val['is_group'] == 1 || $val['promotion'] == 1) {
                    unset($goods[$key]);
                }
            }
            $goods = array_values($goods);
            $data = ['list' => $goods];
        }

        successMsg($data);
    }

    /**
     * ajax 获取商品列表json数据格式
     */
    public function getGoodsListJson()
    {
        $goods = Goods::getAll();
        foreach ($goods as $key => &$val) {
            $val['name'] = $val['goods_name'];
        }
        return json_encode($goods);
    }

    /**
     * 获取商品详情
     */
    public function ajaxGoodsInfo()
    {
        $where['goods_sn'] = $this->requestArr['goods_sn'];

        $info = Goods::getInfo($where);

        successMsg($info);
    }

    /**
     * 添加商品
     */
    public function goodsAdd()
    {
        $post = $this->requestArr;
        $goods_model = $post['goods_model'];
        $promotion = $post['promotion'] ?? 0;
        if ($this->requestMethod == 'POST') {
            $post = $this->requestArr;
            $post['fixed_price'] = array_key_exists('fixed_price', $post) ? 1 : 0;
            $post['promotion'] = array_key_exists('promotion', $post) ? 1 : 0;
            $post['status'] = array_key_exists('status', $post) ? 1 : 0;
            $image = explode(",", $post['goods_img']);
            $post['goods_img'] = $image[0];
            $post['goods_img_list'] = json_encode($image);
            $post['goods_group'] = array_key_exists('goods_group', $post) ? json_encode($post['goods_group']) : '';
            $post['is_group'] = array_key_exists('is_group', $post) ? 1 : 0;
            $post['goods_weight_j'] = $post['goods_weight_j'] ?? 0;
            $post['goods_weight_m'] = $post['goods_weight_m'] ?? 0;
            unset($post['file']);
            unset($post['right-number']);
            unset($post['goods']);
            $post['update_user'] = $this->userArr['user_name'];
            $post['create_user'] = $this->userArr['user_name'];
            $result = Goods::add($post);
            if ($result) {
                successMsg();
            }
            errorMsg('添加失败，请稍后重试');
        }
        $list = GoodsCategory::getList();
        foreach ($list as $key => $val) {
            if ($val['pid'] == 0) {
                unset($list[$key]);
            }
        }

        if ($goods_model == 1) {
            // 添加单个商品
            return view('admin/goods/goodsSingleAdd', ['list' => $list, 'promotion' => $promotion]);
        } else {
            // 添加组合商品
            $goods = Goods::getAll();
            foreach ($goods as $k => &$v) {
                if ($v['goods_sale_num'] == null) {
                    $v['goods_sale_num'] = 0;
                }
                if ($v['is_group'] == 1 || $v['promotion'] == 1) {
                    unset($goods[$k]);
                }
            }
            $goods = array_values($goods);
            return view('admin/goods/goodsMultipleAdd', ['list' => $list, 'goods' => $goods]);
        }
    }

    /**
     * 编辑商品
     */
    public function goodsEdit()
    {
        $post = $this->requestArr;
        $id = $post['id'];
        if ($this->requestMethod == 'POST') {
            $post['fixed_price'] = array_key_exists('fixed_price', $post) ? 1 : 0;
            $post['promotion'] = array_key_exists('promotion', $post) ? 1 : 0;
            $post['status'] = array_key_exists('status', $post) ? 1 : 0;
            // 商品下架需要更新对应的代理商查看商品权限表
            if ($post['status'] == 0) {
                // 获取所有包含该商品ID的权限记录
                $permissions = StoreGoodsViewPermissions::where('goods_ids', 'like', '%' . $id . '%')->get();

                foreach ($permissions as $permission) {
                    // 将逗号分隔的goods_ids转为数组
                    $goodsIds = explode(',', $permission->goods_ids);
                    // 移除下架的商品ID
                    $updatedGoodsIds = array_filter($goodsIds, function ($goodsId) use ($id) {
                        return $goodsId != $id;
                    });
                    // 更新权限记录
                    StoreGoodsViewPermissions::where('id', $permission->id)->update(['goods_ids' => implode(',', $updatedGoodsIds), 'updated_at' => time()]);
                }
            }
            $image = explode(",", $post['goods_img']);
            $post['goods_img'] = $image[0];
            $post['goods_img_list'] = json_encode($image);
            $post['goods_group'] = array_key_exists('goods_group', $post) ? json_encode($post['goods_group']) : '';
            $post['is_group'] = array_key_exists('is_group', $post) ? 1 : 0;
            unset($post['file']);
            unset($post['right-number']);
            $post['update_user'] = $this->userArr['user_name'];
            $result = Goods::edit($id, $post);
            if ($result) {
                successMsg();
            }
            errorMsg('添加失败，请稍后重试');
        }
        $info = Goods::getInfo(['id' => $id]);
        $info['goods_img_list'] = json_decode($info['goods_img_list']);
        $list = GoodsCategory::getList();
        foreach ($list as $key => $val) {
            if ($val['pid'] == 0) {
                unset($list[$key]);
            }
        }

        if ($info['is_group'] == 0) {
            // 编辑单个商品
            return view('admin/goods/goodsSingleEdit', ['info' => $info, 'list' => $list]);
        } else {
            // 编辑组合商品
            $info['goods_group'] = json_decode($info['goods_group'], true);
            $goodsGroup = [];
            $goods = Goods::getAll();
            foreach ($goods as $key => &$val) {
                if ($val['goods_sale_num'] == null) {
                    $val['goods_sale_num'] = 0;
                }
                if ($val['is_group'] == 1 || $val['promotion'] == 1) {
                    unset($goods[$key]);
                    continue;
                }
                foreach ($info['goods_group'] as $v) {
                    if ($v['id'] == $val['id']) {
                        unset($goods[$key]);
                        $tmp = $val;
                        $tmp['number'] = $v['number'];
                        $goodsGroup[] = $tmp;
                    }
                }
            }
            $info['goods_group'] = $goodsGroup;
            return view('admin/goods/goodsMultipleEdit', ['info' => $info, 'list' => $list, 'goods' => $goods]);
        }
    }

    /**
     * 删除商品
     */
    public function goodsDel()
    {
        $id = $this->requestArr['id'];

        $result = Goods::del($id);
        if ($result) {
            successMsg();
        }
        errorMsg('删除失败，请稍后重试');
    }
}